package thread.multi;

//死锁：多个线程相互持有对方所需的资源，然后形成死锁
public class DeadLock {
    public static void main(String[] args) {
        MakeUp sis = new MakeUp(0, "淘气妹妹");
        MakeUp SIS = new MakeUp(1, "安静姐姐");

        sis.start();
        SIS.start();
    }
}

class Lipstick {

}

class Mirror {

}

class MakeUp extends Thread {

    //资源仅有一份，static关键字保证
    private static Lipstick lipstick = new Lipstick();
    private static Mirror mirror = new Mirror();

    int choice = 0;
    String girl;

    public MakeUp(int choice,String name) {
        this.choice = choice;
        this.girl = name;
    }

    @Override
    public void run() {
        try {
            make();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    private void make() throws InterruptedException {
        if (choice == 0) {
            synchronized (lipstick) {
                System.out.println(this.girl + "得到口红，并锁上");
                Thread.sleep(1000);
            }
            synchronized (mirror) {
                System.out.println(this.girl + "得到镜子，并锁上");
            }
        } else {
            synchronized (mirror) {
                System.out.println(this.girl + "得到镜子，并锁上");
                Thread.sleep(1000);
            }
            synchronized (lipstick) {
                System.out.println(this.girl + "得到口红，并锁上");
            }
        }
    }
}
